from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
import re
import binascii
from SerialObject import SerialObject


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 当前窗口需要使用的串口对象
        self.serial = SerialObject(self)
        self.serial.error.connect(self.onSerialObject_error)
        self.serial.statusChanged.connect(self.onSerialObject_statusChanged)
        self.serial.received.connect(self.onSerialObject_received)
        self.serial.connect("COM6", 115200)
        self.resize(500, 300)
    
    def onSerialObject_error(self, e:Exception):
        """ 串口对象发生错误时触发 """
        msg = re.search(r"(\'.*\')", e.args[0])
        if msg:
            msg = msg.group(1)
        else:
            msg = e.args[0]
        QMessageBox.critical(self, "处理串口信息出错", msg);

    def onSerialObject_statusChanged(self, status:bool):
        """ 串口对象的状态发生变化时触发 """
        print("连接状态发生变化，此时为%s" % "连接" if status else "断开")
        if status:
            # 已连接串口
            print('已连接串口')
        else:
            # 已断开串口
            print('已断开串口')


    def onSerialObject_received(self, bs:bytes):
        """ 接受来自串口的数据 """
        print("received bytes, length is:%d" % len(bs))
        print(bs)
        txt = bs.decode("utf-8")
        print(txt)
    
    def keyPressEvent(self, event):
        bs = None
        if event.key() == Qt.Key_Up:
            bs = binascii.a2b_hex("AC0501")
        elif event.key() == Qt.Key_PageUp:
            bs = binascii.a2b_hex("AC0502")
        elif event.key() == Qt.Key_Down:
            bs = binascii.a2b_hex("AC0503")
        elif event.key() == Qt.Key_PageDown:
            bs = binascii.a2b_hex("AC0504")
        elif event.key() == Qt.Key_Space:
            bs = binascii.a2b_hex("AC0505")
        elif event.key() == Qt.Key_Left:
            bs = binascii.a2b_hex("AC0506")
        elif event.key() == Qt.Key_Right:
            bs = binascii.a2b_hex("AC0507")
        elif event.key() == Qt.Key_Enter:
            bs = binascii.a2b_hex("AC0508")
        elif event.key() == Qt.Key_Backspace:
            bs = binascii.a2b_hex("AC0509")
        
        if bs:
            self.serial.send(bs)
        event.accept()

'''  
AC0501 前进 50
AC0502 前进 100
AC0503 后退 50
AC0504 后退 100
AC0505 停止
AC0506 左转
AC0507 右转
AC0508 正转
AC0509 反转
'''

def main():
    app = QApplication(sys.argv)
    window = MainWindow()

    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
